<template>
	<div class="c-center-container">
		<div id="input_title" class="ui input transparent">
			<input v-model="title.name"
			 :readonly="!title.editing"
			 :style="{width: title.name.length*20 + 3 + 'px'}">
			<i class="icon cursor"
			:class="{edit: !title.editing, checkmark: title.editing}"
			@click="editTitle"></i>
		</div>
		<navi :list="list" :isEditable=true
		:currentApi="currentApi"
		@editType="editType"
		@removeType="removeType"
		@addSubtype="addSubtype1"
		@addSubtypeApi="addSubtype2"
		@editSubtype="editSubtype"
		@removeSubtype="removeSubtype"
		@addApi="addApi"
		@editApi="editApi"
		@removeApi="removeApi"
		@clickApi="clickApi"
		@clickCommon="clickCommon">
			<p class="tip" @click="addType">新增大分类</p>
		</navi>
		<div class="c-right-container">
			<!-- 公共部分 -->
			<div v-show="commonShow">
				<div class="ui labeled input">
				  <div class="ui label">
				    请求方式
				  </div>
				  <input placeholder="诚恳的请求"
				  v-model="common.method">
				</div>
				<div class="ui labeled input">
				  <div class="ui label">
				    接口地址
				  </div>
				  <input placeholder="http://11.22.33.44/I_❤_my_api_so_much"
				  v-model="common.api_url">
				</div>
				<div>
					<button class="ui button fr"
					:class="{disabled: btnDisabled}"
					@click="saveCommon">
					  保存
					</button>
				</div>
			</div>
			<!-- 常规部分 -->
			<div v-show="!commonShow">
				<p class="c-title">请求方式</p>
				<div class="ui input fluid">
					<input v-model="current.method">
				</div>
				<p class="c-title">接口地址</p>
				<div class="ui input fluid">
					<input v-model="current.api_url">
				</div>
				<formPart
				:request="current.request"
				:response="current.response"
				isEditable=true
				@addRow="addRow"
				@deleteRow="deleteRow"
				@save="saveApi('auto')"></formPart>
				<div>
					<button class="ui button fr"
					:class="{disabled: btnDisabled}"
					@click="saveApi">
					  保存
					</button>
					<button class="ui button fr"
					@click="post">
					试一哈😶
					</button>
					<pre v-show="current.response_data">{{current.response_data}}</pre>
				</div>
			</div>
		</div>
		<!-- 验证部分 -->
		<pop :popshow="popshow">
      		<div class="ui icon header">用户验证</div>
	      	<div class="content">
	      		<div class="dialog">
	      			<span class="fl">
	      				<i class="meh inverted icon"></i>
	      				<div class="ui left pointing white basic label">
	      				    <div class="ui transparent input">
	      				        <input type="text" readonly="true" value="前方何人？报上名来！">
	      				    </div>
	      				</div>
	      			</span>
	      		</div>
	      		<div class="dialog">
	      			 <span class="fr">
	      			 	<div class="ui right pointing white basic label">
	      			 	    <div class="ui transparent input">
	      			 	        <input type="text"
	      			 	        placeholder="我是…"
	      			 	        v-model="name">
	      			 	    </div>
	      			 	</div>
	      			 	<i class="meh inverted icon"></i>
	      			 </span>
	      		</div>
	      		<div class="dialog" v-if="confirmResponse">
	      			 <span class="fl">
	      			 	<i class="inverted icon"
	      			 	:class="{smile: confirmResponse === 1, frown: confirmResponse === 2}"></i>
	      			 	<div class="ui left pointing white basic label">
	      			 	    <div class="ui transparent input">
	      			 	        <input type="text" readonly="true"
	      			 	       	:value="confirmResponse === 1 ? '快进来歇歇脚吧！' : '对不起，你的血缘不纯正'">
	      			 	    </div>
	      			 	</div>
	      			 </span>
	      		</div>
	      	</div>

	      	<div class="actions">
		        <div class="ui ok inverted button"
		        :class="{basic: !name, yellow: name}"
		        @click="confirmUser">
		          <i class="checkmark icon"></i>请求放行
		    	</div>
	      	</div>
      	</pop>
	</div>
</template>
<script>
import pop from './module/Pop.vue'
import navi from './Navi.vue'
import formPart from './Form.vue'
import AV from '../global.js';
import {myAlert} from '../assets/utils.js';
export default{
	name: 'input',
	mounted(){
		var currentUser = AV.User.current();
		if(currentUser) this.popshow = false;
		this.getData();
	},
	data(){
		return {
			title: {
				name:'',
				editing: false
			},
			list: [],
			current: {
				request: [{
					name: '',
					type: '',
					des: '',
					must: true
				}],
				response: [{
					name: '',
					type: '',
					des: ''
				}],
				api_url: '',
				method: '',
				response_data: ''
			},
			currentApi:'',
			common: {
				api_url: '',
				method: ''
			},
			commonShow: true,
			project:'',
			btnDisabled: false,
			popshow: true,
			// 用户姓名
			name: '',
			confirmResponse: 0
		}
	},
	computed:{
		initialApi(){
			var obj = {
				api_url: this.common.api_url,
				method: this.common.method,
				request:[],
				response:[]
			}
			return JSON.stringify(obj);
		}
	},
	methods:{
		updateProject(obj){
			var pro = AV.Object.createWithoutData('Projects', this.$route.query.id);
			Object.keys(obj).forEach((e) => {
				pro.set(e, obj[e]);
			})
			pro.save();
		},
		// 修改项目名称
		editTitle(){
			if(this.title.editing){
				this.updateProject({
					name: this.title.name
				})
			}
			this.title.editing = !this.title.editing;
			myAlert('修改项目名称成功!');
		},
		addType(){
			var list = {
				name: '我是分类',
				collapse: false,
				editing: true,
				content:[]
			}
			var type = new AV.Object('Types');
			type.set('name', list.name);
			type.set('targetProject', this.project);
			type.save().then((r)=>{
				list.id = r.id;
				this.list.push(list);
			})
		},
		editType(type){
			var t = AV.Object.createWithoutData('Types', type.id);
			t.set('name', type.name);
			t.save().then((r)=>{
				type.editing = false;
				myAlert('分类名修改成功！');
			})
		},
		removeType(type, index){
			var t = AV.Object.createWithoutData('Types', type.id);
			t.destroy().then(() => {
				this.list.splice(index,1);
			})
		},
		addSubtype(type, isApi){
			var list = {
				name: '我是小分类',
				collapse: false,
				editing: true,
				content:[],
				isApi: isApi,
				apiContent: this.initialApi
			}
			var subtype = new AV.Object('Subtypes');
			subtype.set('name', list.name);
			var targetType = AV.Object.createWithoutData('Types', type.id);
			subtype.set('targetType', targetType);
			subtype.set('isApi', isApi);
			if(isApi) subtype.set('apiContent', this.initialApi);
			subtype.save().then((r)=>{
				list.id = r.id;
				type.content.push(list);
			})
		},
		addSubtype1(type){
			this.addSubtype(type, false);
		},
		addSubtype2(type){
			this.addSubtype(type, true);
		},
		editSubtype(subtype){
			var t = AV.Object.createWithoutData('Subtypes', subtype.id);
			t.set('name', subtype.name);
			t.save().then((r)=>{
				subtype.editing = false;
			})
		},
		removeSubtype(subtype, index, type){
			var t = AV.Object.createWithoutData('Subtypes', subtype.id);
			t.destroy().then(() => {
				type.content.splice(index,1);
				myAlert('删除完毕！');
			})
		},
		addApi(subtype){
			var list = {
				name: '我是接口',
				collapse: false,
				editing: true,
				apiContent: this.initialApi
			}
			var api = new AV.Object('Apis');
			api.set('name', list.name);
			var targetSubtype = AV.Object.createWithoutData('Subtypes', subtype.id);
			api.set('targetSubtype', targetSubtype);
			api.set('apiContent', this.initialApi);
			api.save().then((r)=>{
				list.id = r.id;
				subtype.content.push(list);
			})
		},
		editApi(api){
			var t = AV.Object.createWithoutData('Apis', api.id);
			t.set('name', api.name);
			t.save().then((r)=>{
				api.editing = false;
			})
		},
		removeApi(api, index, subtype){
			var t = AV.Object.createWithoutData('Apis', api.id);
			t.destroy().then(() => {
				subtype.content.splice(index,1);
				myAlert('删除完毕！');
			})
		},
		clickApi(api, tableClass){
			this.commonShow = false;
			this.currentApi = api;
			var a = JSON.parse(api.apiContent);
			// 因为要分开两个表保存
			this.current.tableClass = tableClass;
			this.current.id = api.id;
			this.current.api_url = a.api_url || this.common.api_url;
			this.current.method = a.method || this.common.method;
			this.current.request = a.request.length ? a.request : [{
				name: '',
				type: '',
				des: '',
				must: true,
				val:''
			}];
			this.current.response = a.response.length ? a.response : [{
				name: '',
				type: '',
				des: ''
			}]
		},
		saveApi(type){
			this.btnDisabled = true;
			var obj = AV.Object.createWithoutData(this.current.tableClass, this.current.id);
			obj.set('apiContent', JSON.stringify(this.current));
			obj.save().then(() => {
				this.currentApi.apiContent = JSON.stringify(this.current);
				type === 'auto' ? myAlert('帮你自动保存拉…') : myAlert('报告！保存成功！');
				this.btnDisabled = false;
			})
		},
		clickCommon(){
			this.commonShow = true;
		},
		saveCommon(){
			this.btnDisabled = true;
			var pro = AV.Object.createWithoutData('Projects', this.$route.query.id);
			pro.set('common', JSON.stringify(this.common));
			pro.save().then(() => {
				myAlert('报告！保存成功！');
				this.btnDisabled = false;
			})
		},
		addRow(type, index){
			if(type === 'request')
				this.current.request.splice(index+1, 0, {
					des:'',
					type: '',
					name: '',
					must: true
				});
			else
				this.current.response.splice(index+1, 0, {
					des:'',
					type: '',
					name: ''
				});
		},
		deleteRow(type, index){
			if(type === 'request') {
				if(this.current.request.length === 1) return;
				this.current.request.splice(index, 1);
			} else {
				if(this.current.response.length === 1) return;
				this.curent.response.splice(index, 1);
			}
		},
		post(){
			let data = {};
			this.current.request.forEach((e) => {
				data[e.name] = e.val;
			})
			this.$http.post(this.current.api_url, data, {
				emulateJSON: true
			}).then((response) => {
				this.current.response_data = response.body;
			},()=>{
				this.current.response_data = '网络请求失败拉！快去质问王景文！☹';
			})
		},
		confirmUser(){
			if(!this.name) return;
			if(this.name !== '我是王景文') this.confirmResponse = 2;
			else {
				AV.User.logIn('我是王景文', '123456').
				then((loginedUser) => {
				    this.confirmResponse = 1;
				    setTimeout(() => {
				    	this.popshow = false;
				    }, 1000)
				});
			}
		}
	},
	components:{navi, formPart, pop}
}
</script>
<style lang='less' scoped>
	#input_title{
		display: block;
		margin-bottom: 20px;
		input{
			font-size: 20px;
			font-weight: bold;
		}
	}
	input{
		width: 400px;
	}
	.tip{
		float: right;
		font-size: 12px;
		cursor: pointer;
	}
	.ui.labeled.input{
		font-size: 12px;
		margin: 10px 80px;
	}
	.ui.modal{
		.content{
			text-align: center;
		}
		.input{
			width: 15em;
		}
		i.meh,i.smile,i.frown{
			font-size: 1.8em;
			vertical-align: -.2em;
		}
		.dialog{
			width: 400px;
			margin: 0 auto 30px;
			overflow: hidden;
		}
	}
</style>